#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>

void SetNonBlock(int fd)
{
    int f1 = fcntl(fd, F_GETFL);
    if (f1 < 0)
    {
        perror("fctnl error");
        return;
    }
    fcntl(fd, F_SETFL, f1 | O_NONBLOCK);
    std::cout << "set " << fd << " nonblock success" << std::endl;
}

int main()
{
    SetNonBlock(0);
    char buffer[1024];
    while (true)
    {
        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "echo: " << buffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "read done" << std::endl;
            break;
        }
        else
        {
            if (errno == EWOULDBLOCK)
            {
                std::cout << "0 fd data not ready, try again" << std::endl;
            }
            else
            {
                std::cerr << "read error, return-size=" << n << ", errno code:"
                          << errno << ", errno str:  " << strerror(errno) << std::endl;
                break;
            }
            sleep(1);
        }
    }
    return 0;
}